import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter, constantRoutes, allAsyncRoutes, anyRoute } from '@/router'

// 过滤函数 根据返回的路由名称数组过滤出真正的异步路由
  function filterUserAsyncZRoutes(allAsyncRoutes, routeNames){
    // 过滤名称对应的异步路由
    const result = allAsyncRoutes.filter(item => {
      // 判断路由中有没有name值
      if(routeNames.indexOf(item.name) !== -1){
        // 判断子组件有没有路由名称数组,如果有数组长度是否大于0
        if(item.children && item.children.length){
          item.children = filterUserAsyncZRoutes(item.children, routeNames)
        }
        return true // 在返回之前,使用递归方式,继续判断子组件,
      }
  })
  // 返回过滤后的数组
  return result
}


const state = {
  token: getToken(),
  name: '',
  avatar: '',
  buttons:[], //按钮权限数据
  roles:[], //角色数据
  asyncRoutes:[], // 根据字符串过滤后的路由
  routes:[], // 这个用户对应的所有的路由数组, 后边用于动态生成菜单去遍历

}

const mutations = {
  RESET_STATE: (state) => {
    // Object.assign(state, getDefaultState())
    state.token = getToken()
    state.name = ''
    state.avatar = ''
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },

  SET_USERINFO : (state, userInfo)=>{
    state.name = userInfo.name
    state.avatar = userInfo.avatar
  },

  SET_ROUTES:(state, asyncRoutes)=>{
    // 过滤完的路由数组
    state.asyncRoutes = asyncRoutes
    // 最终的用户对应的所有的路由,使用concat把它们拼接起来,后进行动态注册,为了侧边栏动态遍历生成菜单
    state.routes = constantRoutes.concat(asyncRoutes, anyRoute)
    // 动态注册路由(动态添加路由)
    router.addRoutes([...asyncRoutes, anyRoute])
  }


}

const actions = {
  // user login 返回token
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info 返回用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        
        commit('SET_USERINFO', data)
        commit('SET_ROUTES', filterUserAsyncZRoutes(allAsyncRoutes, data.routes))

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

